package com.leetcode.concurrency;

import java.util.concurrent.Semaphore;

class H2O {

    private final Semaphore hSignal;
    private final Semaphore oSignal;

    public H2O() {
        hSignal = new Semaphore(2);
        oSignal = new Semaphore(0);
    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        hSignal.acquire();
        // releaseHydrogen.run() outputs "H". Do not change or remove this line.
        releaseHydrogen.run();
        if(hSignal.availablePermits() == 0)
            oSignal.release();
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        oSignal.acquire();
        // releaseOxygen.run() outputs "O". Do not change or remove this line.
        releaseOxygen.run();
        hSignal.release(2);
    }
}
